import { Radio } from "antd";
import { useEffect, useState } from "react";
import "@/index.css";
import "./style.less";
import TextArea from "antd/es/input/TextArea";

interface ExtendedGraphProps {
  url: string;
}

const relative_size_array = [
  {
    value: "4:3",
    label: "4:3",
  },
  {
    value: "3:2",
    label: "3:2",
  },
  {
    value: "16:9",
    label: "16:9",
  },
  {
    value: "3:4",
    label: "3:4",
  },
  {
    value: "2:3",
    label: "2:3",
  },
  {
    value: "9:16",
    label: "9:16",
  },
];

function getImageSize(
  src: string,
  callback: (obj: { width: number; height: number }) => void
) {
  // 创建一个新的Image对象
  const img = new Image();

  // 当图片加载完成时，执行回调函数
  img.onload = function () {
    callback({
      width: img.width,
      height: img.height,
    });
  };

  // 如果图片已经缓存，onload事件可能不会触发，所以设置img.src
  img.src = src;
}

// 计算最大公约数
function gcd(a: number, b: number) {
  while (b !== 0) {
    const t = b;
    b = a % b;
    a = t;
  }
  return a;
}

interface IPosObj {
  [x: string]: string;
}

const posObj: IPosObj = {
  top: "top",
  bottom: "bottom",
  center: "center",
  left: "left",
  right: "right",
};

export const ExtendedGraphBG = (props: ExtendedGraphProps) => {
  const { url } = props;
  const [relativePos, setRelativePos] = useState<string>("center");
  const [relativeSize, setRelativeSize] = useState<string>("4:3");
  const [relativeSizeRatio, setRelativeSizeRatio] = useState<number>(4 / 3);
  const [backgroundPosition, setBackgroundPosition] = useState("center");
  const [imgOriginWidth, setImgOriginWidth] = useState(0);
  const [imgOriginHeight, setImgOriginHeight] = useState(0);
  const [imgContainerWidth, setImgContainerWidth] = useState<number | string>(
    0
  );
  const [imgContainerHeight, setImgContainerHeight] = useState<number | string>(
    0
  );
  const [simplifiedRatio, setSimplifiedRatio] = useState("");
  const [simplifiedRatioValue, setSimplifiedRatioValue] = useState(0);

  const resetPosToCenter = () => {
    setRelativePos("center");
    setBackgroundPosition("center");
  };

  useEffect(() => {
    resetPosToCenter();
    getImageSize(url, (obj) => {
      setImgOriginWidth(obj.width);
      setImgOriginHeight(obj.height);
      const ratio = [obj.width, obj.height];
      // 简化比例
      const simplifiedRatio = ratio.map((num) => num / gcd(ratio[0], ratio[1]));
      setSimplifiedRatio(`${simplifiedRatio[0]}:${simplifiedRatio[1]}`);
      setSimplifiedRatioValue(simplifiedRatio[0] / simplifiedRatio[1]);
    });
    return () => {};
  }, [url]);

  useEffect(() => {
    resetPosToCenter();
  }, [relativeSize]);

  useEffect(() => {
    const relativeWidth = +relativeSize.split(":")[0];
    const relativeHeight = +relativeSize.split(":")[1];
    let _imgContainerWidth = 0;
    let _imgContainerHeight = 0;
    if (relativeWidth > relativeHeight) {
      // 宽比高长
      _imgContainerWidth = 288;
      _imgContainerHeight = 288 * (relativeHeight / relativeWidth);
    } else {
      // 宽比高短
      _imgContainerWidth = 288 * (relativeWidth / relativeHeight);
      _imgContainerHeight = 288;
    }
    setImgContainerWidth(_imgContainerWidth);
    setImgContainerHeight(_imgContainerHeight);
  }, [relativeSize, imgOriginWidth, imgOriginHeight]);

  const changeRelativePos = (pos: string) => {
    const relativeWidth = +relativeSize.split(":")[0];
    const relativeHeight = +relativeSize.split(":")[1];
    const imgOriginWidthHeightRatio = imgOriginWidth / imgOriginHeight;
    const relativeWidthHeightRatio = relativeWidth / relativeHeight;
    if (imgOriginWidthHeightRatio > relativeWidthHeightRatio) {
      if (pos === "left" || pos === "right") return;
      setRelativePos(pos);
      setBackgroundPosition(posObj[pos]);
    } else if (imgOriginWidthHeightRatio === relativeWidthHeightRatio) {
      return;
    } else {
      if (pos === "up" || pos === "bottom") return;
      setRelativePos(pos);
      setBackgroundPosition(posObj[pos]);
    }
  };

  const PosBtn = (pos: string) => {
    return relativePos === pos ? (
      <span className="h-[20px] w-[20px] bg-[#3161FF]"></span>
    ) : (
      <span className="h-[4px] w-[4px] bg-[#3161FF]"></span>
    );
  };

  const SudokuItem = (pos: string, extraClass?: string) => (
    <div
      className={`grid-item ${extraClass}`}
      onClick={() => {
        changeRelativePos(pos);
      }}
    >
      {PosBtn(pos)}
    </div>
  );

  return (
    <div>
      <div id="imgArea">
        <div
          id="imgContainer"
          className="border-[1px] border-dashed border-[#ffffff] bg-black bg-contain bg-no-repeat"
          style={{
            width: imgContainerWidth,
            height: imgContainerHeight,
            backgroundImage: `url(${url})`,
            backgroundPosition,
          }}
        />
        <div className="mt-2">
          图片原比例: {simplifiedRatio} 比例值: {simplifiedRatioValue}
        </div>
        <div>
          选择的比例: {relativeSize} 比例值: {relativeSizeRatio.toFixed(2)}
        </div>
        <p className="w-[500px] text-wrap">
          结论：图片缩放宽高，取决于图片宽高比和容器宽高比的大小，如果图片宽高比大于容器宽高比，图片适应容器受宽影响，则收缩宽至容器宽，高度自适应;如两者相等，则图片宽高等于容器宽高;
          如果图片宽高比小于容器宽高比，图片适应容器受高影响，则收缩高至容器高，宽度自适应
        </p>
      </div>
      <div className="flex gap-2 items-center mt-2">
        <div className={`h-[88px] w-[88px] bg-[#2E333B] nine-grid`}>
          {SudokuItem("up", "col-span-3")}
          {SudokuItem("left")}
          {SudokuItem("center")}
          {SudokuItem("right")}
          {SudokuItem("bottom", "col-span-3")}
        </div>
        <Radio.Group
          defaultValue={relativeSize}
          value={relativeSize}
          onChange={(e) => {
            setRelativeSize(e.target.value);
            setRelativeSizeRatio(
              e.target.value.split(":")[0] / e.target.value.split(":")[1]
            );
          }}
          buttonStyle="solid"
        >
          {relative_size_array.map((item, index) => (
            <Radio.Button key={index} value={item.value}>
              {item.label}
            </Radio.Button>
          ))}
        </Radio.Group>
      </div>
      <div className="mt-2">
        图片案例
        <div className="w-[500px] text-wrap">
          横向长图:{" "}
          <TextArea
            value={
              "https://android-imgs.25pp.com/fs08/2022/09/19/0/c301e270a2dca409633b9bb91bc8cc25.png?x-oss-process=image/watermark,image_d2RqX2ljb24ucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMzA=,x_30,y_20,t_75"
            }
          />
        </div>
        <div className="w-[500px] text-wrap">
          纵向长图:{" "}
          <TextArea
            value={
              "https://im2.book.com.tw/image/getImage?i=https://www.books.com.tw/img/M01/013/14/M010131437.jpg&v=61305351k&w=348&h=348"
            }
          />
        </div>
        <div className="w-[500px] text-wrap">
          正方形图:{" "}
          <TextArea
            value={
              "https://www.tailwindcss.cn/favicons/apple-touch-icon.png?v=3"
            }
          />
        </div>
      </div>
    </div>
  );
};
